﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using System.Collections.Specialized;
using Windows.Storage;

using System.IO; //Pour le stream

using Windows.Storage.Streams;
using System.Runtime.Serialization;//Pour la serialization
using MyVideoManager2.DataModel.simple;


namespace MyVideoManager2.Data
{
    //TODO: Renommer GameDossier en MyVideoManager2
    public class Data : MyVideoManager2.Common.BindableBase
    {


        


        private static ObservableCollection<Dossier> _allGroups = new ObservableCollection<Dossier>();
        public static ObservableCollection<Dossier> AllGroups
        {
            get { return _allGroups; }
            set { _allGroups=value; }
        }
        //TODO: GetDossiers = GetDossiers (Le "s" est important)
        /*
        public static IEnumerable<Dossier> GetDossiers(string uniqueId)
        {
            if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a Dossier1.Items of groups");
            
            return AllGroups;
        }
        */
        public static Dossier GetDossier(string uniqueId)
        {
            // Une simple recherche linéaire est acceptable pour les petits groupes de données
            var matches = AllGroups.Where((Dossier) => Dossier.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }
        public static void addDossier(Dossier monDossier)
        {
            AllGroups.Add(monDossier);

        }


        public static Film GetFilm(string uniqueId)
        {
            // Une simple recherche linéaire est acceptable pour les petits groupes de données
            var matches = AllGroups.SelectMany(Dossier => Dossier.Items).Where((item) => item.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }


        public Data()
        {
            var Dossier1 = new Dossier("Films","123","/","C:/");

            Dossier1.Items.Add(new Film("0001", "Tron", "Sam Flynn", ".", Dossier1, genreFilm.ACTION, genreFilm.COMEDIE, "Film pas trop mal", 2012, 5, "Tron"));

            /*
            OM_Dossier OM_Dossier2 = new OM_Dossier("Favoris", Guid.NewGuid().ToString("N"), "/", "D:/", new Peripherique("D:/"));
            OM_Dossier OM_Dossier3 = new OM_Dossier("Cultes", Guid.NewGuid().ToString("N"), "/", "F:/", new Peripherique("F:/"));


            OM_Dossier2.getLstFilms().Add(new OM_Film(Guid.NewGuid().ToString("N"), "Iron Man", "Jon Favreau", ".", OM_Dossier2, MyVideoManager2.Data.genreFilm.ACTION, MyVideoManager2.Data.genreFilm.COMEDIE, "Super film", 2012, 5, "Iron Man"));
            OM_Dossier2.getLstFilms().Add(new OM_Film(Guid.NewGuid().ToString("N"), "Avengers", "Joss Whedon", ".", OM_Dossier2, MyVideoManager2.Data.genreFilm.ACTION, MyVideoManager2.Data.genreFilm.COMEDIE, "Gros budget", 2012, 5, "Avengers"));
            OM_Dossier3.getLstFilms().Add(new OM_Film(Guid.NewGuid().ToString("N"), "Superman", "Richard Donner", ".", OM_Dossier3, MyVideoManager2.Data.genreFilm.ACTION, MyVideoManager2.Data.genreFilm.COMEDIE, "Classique", 2012, 5, "Superman"));
            OM_Dossier3.getLstFilms().Add(new OM_Film(Guid.NewGuid().ToString("N"), "Batman", "Christopher Nolan", ".", OM_Dossier3, MyVideoManager2.Data.genreFilm.ACTION, MyVideoManager2.Data.genreFilm.COMEDIE, "Ne changera jamais", 2012, 5, "Batman"));

            
            // on serialise la liste de dossier test
            OM_Dossier.lstDossier.Add(OM_Dossier2);
            OM_Dossier.lstDossier.Add(OM_Dossier3);
            

            */

            //OM_serialisation();
            OM_deserialisation();

            
            /*
            var Dossier2 = new Dossier("Films", "456", "/", "D:/", new Peripherique("D:/"));
            Dossier2.Items.Add(new Film("Film-2", "Tron", "Sam Flynn", ".", Dossier2, genreFilm.ACTION, genreFilm.COMEDIE, "Film pas trop mal", 2012, 5, "Tron"));
             * */
            //Dossier1.Items.ElementAt(0).LstActeur.Add("Sam Flynn");

            if (AllGroups.Count == 0)
            {
                AllGroups.Add(Dossier1);
                transferOmToOC(); 
            }

         //   AllGroups.Add(Dossier2);
            /*var Dossier1 = new Dossier("NES","Dossier-1","Assets/nintendo-nes.png");
            this.AllGroups.Add(Dossier1);
            Dossier1.Items.Add(new Film("Alien 3 : Title Screen", "http://www.bee-ware.ch/nescenter/alien3_titlescreen.mp3",Dossier1));
            */

        }
        #region OM_Serialisation
        private static string fichier = @"data.xml";
        public static async void OM_serialisation()
        {
            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fichier, CreationCollisionOption.ReplaceExisting);
            IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite);
            IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
            var sessionSerializer = new DataContractSerializer(typeof(List<OM_Dossier>), new Type[] { typeof(OM_Dossier) });
            sessionSerializer.WriteObject(sessionOutputStream.AsStreamForWrite(), OM_Dossier.lstDossier);
            await sessionOutputStream.FlushAsync();

        }

      
        public async void OM_deserialisation()
        {

            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fichier, CreationCollisionOption.OpenIfExists);
            if (sessionFile == null)
            {
                return;
            }
            IInputStream sessionInputStream = await sessionFile.OpenReadAsync();
            var sessionSerializer = new DataContractSerializer(typeof(List<OM_Dossier>), new Type[] { typeof(OM_Dossier) });

            if (sessionInputStream.AsStreamForRead().Length > 0)
            {
                OM_Dossier.lstDossier = (List<OM_Dossier>)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead());
            }
        }

        #endregion


        public void transferOmToOC()
        {
            foreach (OM_Dossier monDossier in OM_Dossier.lstDossier)
            {
                //on crée le dossier
                Dossier nouveauDossier = new Dossier(monDossier.nomDossier, monDossier.uniqueId,monDossier.imagePath, monDossier.cheminDossier);

                foreach (OM_Film monFilm in monDossier.lstFilms)
                {
                    Film nouveauFilm = new Film(monFilm.uniqueId, monFilm.titreFilm, monFilm.realisateurFilm, monFilm.cheminFilm, nouveauDossier, monFilm.genrePrincipal, monFilm.genreSecondaire, monFilm.descriptionFilm, monFilm.anneeSortie, monFilm.anneeSortie, monFilm.titreFilmOriginal);
                    nouveauDossier.Items.Add(nouveauFilm);
                }


                AllGroups.Add(nouveauDossier);
            }
        }



      

    }
}
